package com.novel.disk.controller;

import com.novel.disk.common.BaseController;
import com.novel.disk.common.Result;
import com.novel.disk.framework.config.LoginProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 用户 控制器
 *
 * @author novel
 * @date 2020/7/24
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    private final RestTemplate restTemplate;
    private final LoginProperties loginProperties;

    public UserController(RestTemplate restTemplate, LoginProperties loginProperties) {
        this.restTemplate = restTemplate;
        this.loginProperties = loginProperties;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        return toAjax(getUser());
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token) {
        String url = loginProperties.getUrl() + "/logout";
        HttpHeaders header = new HttpHeaders();
        header.set("Authorization", token);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(header);
        ResponseEntity<Result> entity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Result.class);
        return toAjax(entity.getBody());
    }
}
